//
//  XZCollectSourceVC.m
//  Teecloud
//
//  Created by PC on 2018/10/31.
//  Copyright © 2018年 小志. All rights reserved.
//

#import "XZCollectSourceVC.h"
#import "GMHomeImgCell.h"
#import "GMHomeTableViewCell.h"
#import "GMStudyResModel.h"
#import "GMBuyVideoVC.h"
#import "GMPlayerViewController.h"
#import "GMReadPDFVC.h"
#import "GMCoursePackageVC.h"
#import "GMExercisesVC.h"
#import "GMExaminationVC.h"
#import "GMBuyFile.h"
#import "XZSearchBar.h"
@interface XZCollectSourceVC ()<UITableViewDelegate,UITableViewDataSource,UISearchBarDelegate>
@property (nonatomic, strong) UITableView *tabView;
@property (nonatomic, assign) NSInteger page;
@property (nonatomic, copy) NSString *key;
@property (nonatomic, strong) XZSearchBar *searchBar;
@property (nonatomic, strong) NSMutableArray *dataArr;
@end

@implementation XZCollectSourceVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = kWhiteColor;
    [self creatTitleView];
    self.page = 0;
    [self getNewStudyData];
}
-(void)getNewStudyData{
    self.page =0;
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setValue:FROM_IOS forKey:@"from"];
    [dict setValue:[XGMArchiverTools cacheForKey:BUSIORGID] forKey:@"busiOrgId"];
    [dict setValue:[XGMArchiverTools cacheForKey:USER_UserId] forKey:@"userId"];
    [dict setValue:[XGMArchiverTools cacheForKey:USER_identifierNumber] forKey:@"loginFinger"];
    [dict setValue:@(self.page) forKey:@"pageIndex"];
    [dict setValue:self.key forKey:@"key"];
    kWeakObject(self)
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [HJNetwork HTTPWithMethod:HJRequestMethodPOST url:[NSString stringWithFormat:@"ajax-api.ashx?$c=TeeyunApp&$m=GetMyCollectList&$v=%@",VERSION] parameters:dict cachePolicy:HJCachePolicyIgnoreCache callback:^(id responseObject, NSError *error) {
        [MBProgressHUD hideHUDForView:weakself.view animated:YES];
        [weakself.tabView.mj_header endRefreshing];
        [weakself.tabView.mj_footer endRefreshing];
        if (!error) {
            if ([[responseObject objectForKey:RESULT_NAME_Success] boolValue]) {
                NSArray *arr = [GMStudyResModel mj_objectArrayWithKeyValuesArray:[responseObject objectForKey:RESULT_NAME_Data]];
                [weakself.dataArr removeAllObjects];
                [weakself.dataArr addObjectsFromArray:arr];
                if (weakself.dataArr.count == 0) {
                    [weakself.tabView setupEmptyDataText:@"暂无数据" secoundText:@"" buttonTit:@"" verticalOffset:0 emptyImage:NODATAIMG tapBlock:^{
                        
                    } butClick:^{
                        
                    }];
                }
                [weakself.tabView reloadData];
            }
        }else{
            [MBProgressHUD showErrorOrSuc:@"网络异常" toView:weakself.view];
        }
    }];
}
-(void)getMoreStudyData{
    self.page ++;
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setValue:FROM_IOS forKey:@"from"];
    [dict setValue:[XGMArchiverTools cacheForKey:BUSIORGID] forKey:@"busiOrgId"];
    [dict setValue:[XGMArchiverTools cacheForKey:USER_UserId] forKey:@"userId"];
    [dict setValue:[XGMArchiverTools cacheForKey:USER_identifierNumber] forKey:@"loginFinger"];
    [dict setValue:@(self.page) forKey:@"pageIndex"];
    [dict setValue:self.key forKey:@"key"];
    [HJNetwork HTTPWithMethod:HJRequestMethodPOST url:[NSString stringWithFormat:@"ajax-api.ashx?$c=TeeyunApp&$m=GetMyCollectList&$v=%@",VERSION] parameters:dict cachePolicy:HJCachePolicyIgnoreCache callback:^(id responseObject, NSError *error) {
        if (!error) {
            if ([[responseObject objectForKey:RESULT_NAME_Success] boolValue]) {
                NSArray *arr = [GMStudyResModel mj_objectArrayWithKeyValuesArray:[responseObject objectForKey:RESULT_NAME_Data]];
                [self.dataArr addObjectsFromArray:arr];
                if (arr.count > 0) {
                    [self.tabView.mj_footer endRefreshing];
                    [self.tabView.mj_header endRefreshing];
                }else{
                    self.tabView.mj_footer.state = MJRefreshStateNoMoreData;
                }
                [self.tabView reloadData];
            }
        }else{
            [MBProgressHUD showErrorOrSuc:@"请求出错" toView:self.view];
        }
    }];
}
//当键退出
- (void)keyboardWillHide:(NSNotification *)notification
{
    self.key = self.searchBar.text;
    [self getNewStudyData];
}
#pragma mark - UISearchBarDelegate
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    [searchBar resignFirstResponder];
}

- (void)creatTitleView{
    UIView *titleView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, DEVICE_WIDTH, 44)];
    titleView.backgroundColor = [UIColor clearColor];
    //设置titleview，不过这个view并不是我们需要的居中的view；
    self.navigationItem.titleView = titleView;
    __weak typeof(self) weakSelf = self;
    //主线程列队一个block， 这样做 可以获取到autolayout布局后的frame，也就是titleview的frame。在viewDidLayoutSubviews中同样可以获取到布局后的坐标
    __block XZSearchBar *searchBar;
    dispatch_async(dispatch_get_main_queue(), ^{
        //要居中view的宽度
        CGFloat width = 240;
        //实际居中的view
        UIView *centerView = [[UIView alloc]init];
        centerView.backgroundColor = kClearColor;
        //设置一个基于window居中的坐标
        centerView.frame = CGRectMake((DEVICE_WIDTH-width)/2, 20+(kIs_iPhoneX?24:0), width, 44);
        //坐标系转换到titleview
        centerView.frame = [weakSelf.view.window convertRect:centerView.frame toView:weakSelf.navigationItem.titleView];
        searchBar = [[XZSearchBar alloc]initWithFrame:CGRectMake(0, 10, 240, 30)];
        searchBar.delegate = self;
        searchBar.placeholder = @"输入关键字";
        searchBar.tintColor = kBlueColor;
        [centerView addSubview:searchBar];
        self.searchBar = searchBar;
        //centerview添加到titleview
        [weakSelf.navigationItem.titleView addSubview:centerView];
    });
}
-(NSMutableArray *)dataArr{
    if (!_dataArr) {
        _dataArr = [[NSMutableArray alloc] init];
    }
    return _dataArr;
}
-(UITableView *)tabView{
    if (!_tabView) {
        _tabView = [UITableView zj_tableViewWithSuperview:self.view delegate:self style:UITableViewStylePlain constraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self.view);
        }];
        _tabView.separatorStyle =UITableViewCellSeparatorStyleNone;
        [_tabView registerNib:[UINib nibWithNibName:@"GMHomeImgCell" bundle:nil] forCellReuseIdentifier:@"GMHomeImgCell"];
        [_tabView registerNib:[UINib nibWithNibName:@"GMHomeTableViewCell" bundle:nil] forCellReuseIdentifier:@"GMHomeTableViewCell"];
        _tabView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(getNewStudyData)];
        _tabView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(getMoreStudyData)];
    }
    return _tabView;
}
#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    GMStudyResModel *stuModel = self.dataArr[indexPath.row];
    if (stuModel.IsAd) {
        GMHomeImgCell *imgCell = [tableView dequeueReusableCellWithIdentifier:@"GMHomeImgCell" forIndexPath:indexPath];
        imgCell.stuModel = stuModel;
        return imgCell;
    }else{
        GMHomeTableViewCell *stuCell = [tableView dequeueReusableCellWithIdentifier:@"GMHomeTableViewCell" forIndexPath:indexPath];
        stuCell.stuModel = stuModel;
        return stuCell;
    }
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 80;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    GMStudyResModel *model = self.dataArr[indexPath.row];
    if (model.IsAd) {//广告 就更新阅读计数
        [self updateReadCount:model.Id];
    }
    if (model.NormalCode >0) {
        if (model.NormalCode ==1) {
            [MBProgressHUD showErrorOrSuc:@"关联资源已下架或不可用" toView:self.view];
        }else if (model.NormalCode ==2){
            [MBProgressHUD showErrorOrSuc:@"当前手机型 号非购买资源所用手机型号，你可以到“我的 - 主页 - 个人资料(付费资源管理)”模块申请变更手机型号。" toView:self.view];
        }else if (model.NormalCode ==3){
            [MBProgressHUD showErrorOrSuc:@"本期培训已结束，课件自动关闭；若有需要请报名参加下期培训。" toView:self.view];
        }
        
    }else{
        if ([model.ResType isEqualToNumber:@(1)]) {
            /**视频*/
            if (model.IsFree) {
                GMPlayerViewController *play = [[GMPlayerViewController alloc] init];
                play.resId = model.Id;
                [self.navigationController pushViewController:play animated:YES];
            }else{
                GMBuyVideoVC *vc = [[GMBuyVideoVC alloc] init];
                vc.resId = model.Id;
                vc.ResType = model.ResType;
             
                [self.navigationController pushViewController:vc animated:YES];
            }
            
        }else if ([model.ResType isEqualToNumber:@(2)]){
            /**文档*/
            if (model.IsFree) {
                GMReadPDFVC *file = [[GMReadPDFVC alloc] init];
                file.resId = model.Id;
                [self.navigationController pushViewController:file animated:YES];
            }else{
                GMBuyFile *file = [[GMBuyFile alloc] init];
             
                file.resId = model.Id;
                file.ResType = model.ResType;
                [self.navigationController pushViewController:file animated:YES];
            }
            
        }else if ([model.ResType isEqualToNumber:@(3)]){
            /**习题*/
            if (model.IsFree) {
                GMExercisesVC *exercises =[[GMExercisesVC alloc] init];
                exercises.resId = model.Id;
                [self.navigationController pushViewController:exercises animated:YES];
            }else{
                GMBuyFile *file = [[GMBuyFile alloc] init];
              
                file.resId = model.Id;
                file.ResType = model.ResType;
                [self.navigationController pushViewController:file animated:YES];
            }
            
        }else if ([model.ResType isEqualToNumber:@(4)]){
            /**试卷*/
            if (model.IsFree) {
                GMExaminationVC *exam = [[GMExaminationVC alloc] init];
                exam.resId = model.Id;
                [self.navigationController pushViewController:exam animated:YES];
            }else{
                GMBuyFile *file = [[GMBuyFile alloc] init];
              
                file.resId = model.Id;
                file.ResType = model.ResType;
                [self.navigationController pushViewController:file animated:YES];
            }
            
        }else if ([model.ResType isEqualToNumber:@(9)]){
            /**课程包*/
            
            if (model.IsFree) {
                GMCoursePackageVC *package = [[GMCoursePackageVC alloc] init];
                package.resId = model.Id;
                package.titleStr = model.Name;
                [self.navigationController pushViewController:package animated:YES];
            }else{
                GMBuyFile *file = [[GMBuyFile alloc] init];
              
                file.resId = model.Id;
                file.ResType = model.ResType;
                [self.navigationController pushViewController:file animated:YES];
            }
        }
    }
    
}
/*
 *更新广告阅读计数
 */
-(void)updateReadCount:(NSString *)addId{
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setValue:FROM_IOS forKey:@"from"];
    [dict setValue:[XGMArchiverTools cacheForKey:BUSIORGID] forKey:@"busiOrgId"];
    [dict setValue:[XGMArchiverTools cacheForKey:USER_UserId] forKey:@"userId"];
    [dict setValue:[XGMArchiverTools cacheForKey:USER_identifierNumber] forKey:@"loginFinger"];
    //广告Id
    [dict setValue:addId forKey:@"adId"];
    
    [HJNetwork POSTWithURL:[NSString stringWithFormat:@"/ajax-api.ashx?$c=TeeyunApp&$m=UpdateAdCount&$v=%@",VERSION] parameters:dict cachePolicy:HJCachePolicyIgnoreCache callback:^(id responseObject, NSError *error) {
        if (!error) {
            if ([[responseObject objectForKey:RESULT_NAME_Success] boolValue]) {
                XZLog(@"计数成功");
            }else{
                XZLog(@"计数失败");
            }
            
        }else{
            XZLog(@"%@",error);
        }
    }];
}
@end
